package cn.zhage.aimin.gateway1.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.zhage.aimin.gateway1.auth.LoginCheckStrategy;
import cn.zhage.aimin.gateway1.auth.StrategyFactory;
import cn.zhage.aimin.satoken1.admin.AdminStpUtil;
import cn.zhage.aimin.satoken1.user.UserStpUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.util.UriComponentsBuilder;

/*
 *
 * @author 渣哥
 */
@Configuration
public class SaTokenConfigure {
    // 注册 Sa-Token全局过滤器
    @Bean
    public SaReactorFilter getSaReactorFilter() {

        return new SaReactorFilter()
                // 指定 [拦截路由]
                .addInclude("/**")    /* 拦截所有path */
                // 指定 [放行路由]
                .addExclude("/test/userLogin")
                .addExclude("/test/adminLogin")


                // 指定[认证函数]: 每次请求执行
                .setAuth(obj -> {
                    String url = SaHolder.getRequest().getUrl();
                    String s = extractPath(url);
                    LoginCheckStrategy strategy = StrategyFactory.getStrategy(s);
                    strategy.checkAuth();



                })
                // 指定[异常处理函数]：每次[认证函数]发生异常时执行此函数
                .setError(e -> {
                    System.out.println("---------- sa全局异常 ");
                    return SaResult.error(e.getMessage());
                });
    }



    public String extractPath(String urlString) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(urlString);
        String path = builder.build().getPath();
        // 移除开头的 '/'
        assert path != null;
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        return path;
    }
}
